/**
 * 该组件是antd-mobile toast.loading的替代
 */

import React from 'react';
import ReactDOM from 'react-dom';
import { Icon } from 'antd-mobile';
import './loading.css';

class Loading extends React.Component {
    constructor (props) {
        super(props);

        this.state = {
        };

        this.storage = {
        };
    }

    componentWillMount () {
    }

    static show (text = '', duration) {
        const wrapper = Loading._createWrapper();

        ReactDOM.render(
            <Loading text={text}></Loading>,
            wrapper
        );

        if (typeof duration !== 'undefined' && duration > 0) {
            setTimeout(() => {
                Loading.instances[wrapper.id].hide();
            }, duration);
        }

        return Loading.instances[wrapper.id];
    }

    static hide () {
        document.querySelectorAll('.vc-loading-wrapper').forEach((element) => {
            element.remove();
            delete Loading.instances[element.id];
            Loading.instances.length--;
        });
    }

    static _createWrapper () {
        const wrapper = document.createElement('div');

        Loading.instances.length++;

        wrapper.id = `vc-loading-wrapper-${Loading.instances.length}`;
        wrapper.className = 'vc-loading-wrapper';

        Loading.instances[wrapper.id] = {
            element: wrapper,
            hide: function () {
                if (Loading.instances && Loading.instances[this.element.id]) {
                    if (this.element.remove) {
                        this.element.remove();
                    }
                    else {
                        document.body.removeChild(this.element);
                    }
                    delete Loading.instances[this.element.id];
                    Loading.instances.length--;
                }
            }
        };

        return document.body.appendChild(wrapper);
    }

    render () {
        return (
            <div className="loading">
                <div className="mask"></div>
                <div className="cont">
                    <p className="icon"><Icon type="loading" size="lg"></Icon></p>
                    <p className="text">{this.props.text}</p>
                </div>
            </div>
        );
    }
}

Loading.instances = {
    length: 0
};

export default Loading;
